<template>
  <div class="category-management">
    <el-card class="box-card">
      <!-- 修改工具栏样式 -->
      <div class="toolbar">
        <div class="left">
          <!-- 将来如果需要可以在这里添加搜索等功能 -->
        </div>
        <div class="right">
          <el-button type="primary" @click="handleAdd">新增类别</el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="categoryName" label="类别名称"></el-table-column>
        <el-table-column prop="categoryDescription" label="类别描述"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

      <!-- 新增/编辑对话框 -->
      <el-dialog :title="dialogType === 'add' ? '新增类别' : '编辑类别'" 
                 :visible.sync="dialogVisible" 
                 width="500px">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <el-form-item label="类别名称" prop="categoryName">
            <el-input v-model="form.categoryName" placeholder="请输入类别名称"></el-input>
          </el-form-item>
          <el-form-item label="类别描述" prop="categoryDescription">
            <el-input type="textarea" 
                      v-model="form.categoryDescription" 
                      placeholder="请输入类别描述"
                      :rows="3"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'CategoryManagement',
  data() {
    return {
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogType: 'add',
      form: {
        id: null,
        categoryName: '',
        categoryDescription: ''
      },
      rules: {
        categoryName: [
          { required: true, message: '请输入类别名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        categoryDescription: [
          { required: true, message: '请输入类别描述', trigger: 'blur' },
          { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        const response = await this.$http.post('/job-category/page', {
          current: this.currentPage,
          size: this.pageSize
        })
        if (response.data.code === 200) {
          this.tableData = response.data.data.records
          this.total = response.data.data.total
        } else {
          this.$message.error(response.data.msg || '获取类别列表失败')
        }
      } catch (error) {
        console.error('获取类别列表失败:', error)
        this.$message.error('获取类别列表失败')
      } finally {
        this.loading = false
      }
    },
    handleAdd() {
      this.resetForm()
      this.dialogType = 'add'
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.resetForm()
      this.dialogType = 'edit'
      this.form = {
        id: row.id,
        categoryName: row.categoryName,
        categoryDescription: row.categoryDescription
      }
      this.dialogVisible = true
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该类别?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.get(`/job-category/delete/${row.id}`)
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          this.fetchData()
        } else {
          this.$message.error(response.data.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const url = this.dialogType === 'add' ? '/job-category/add' : '/job-category/update'
            const response = await this.$http.post(url, {
              id: this.form.id,
              categoryName: this.form.categoryName,
              categoryDescription: this.form.categoryDescription
            })
            if (response.data.code === 200) {
              this.$message.success(this.dialogType === 'add' ? '添加成功' : '修改成功')
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(response.data.msg || (this.dialogType === 'add' ? '添加失败' : '修改失败'))
            }
          } catch (error) {
            console.error(this.dialogType === 'add' ? '添加失败:' : '修改失败:', error)
            this.$message.error(this.dialogType === 'add' ? '添加失败' : '修改失败')
          }
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    formatDateTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    resetForm() {
      this.form = {
        id: null,
        categoryName: '',
        categoryDescription: ''
      }
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.resetFields()
      })
    }
  }
}
</script>

<style scoped>
.category-management {
  padding: 20px;
}
.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.toolbar .left {
  /* 为将来可能添加的搜索功能预留空间 */
  flex: 1;
}
.toolbar .right {
  /* 右侧按钮区域 */
  text-align: right;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 